const router=require('./router') 
const Koa = require('koa');
const IO = require('koa-socket-2');
const app = new Koa();
const bodyParser = require('koa-bodyparser')
const server = require('koa-static')
const fs = require('fs')
const path = require('path')



const pages = server(path.resolve('build'))


const model = require('./model')

const Chat = model.getModel('chat')

const io = new IO();
// 使用ctx.body解析中间件


app.use(pages)
app.use(bodyParser())

//还可以是用ReadStream，更简单
app.use(async(ctx, next) => {
  let url=ctx.url
  if(url.indexOf('/user')!==-1){
    return await next()
  }
    ctx.type = 'html';
    return  ctx.body = fs.createReadStream(path.resolve('build/index.html'));
});

// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())

io.attach(app);

io.on( 'connection', sock => {
  console.log('建立连接了')
});





io.on('sendmsg', (ctx, data) => {
  console.log( data);
  const {from,to,msg} = data;
  console.log(data)
  const chatid = [from,to].sort().join('_')
  Chat.create({chatid,from,to,content:msg},function(err,doc){
    io.broadcast('recvmsg',Object.assign({},doc._doc))
  })
});


app.listen(9093, () => {
  console.log('server is starting at port 9093')
})